<template>
  <div ref="tagRef" v-if="tags.size">
    <el-scrollbar ref="elScrollRef" :max-height="160">
      <el-tag
        v-for="[name, { type }] in tags"
        :key="name"
        :type="type"
        class="tag-item"
        @click="selectTag(name)"
      >
        {{ name }}
      </el-tag>
      <SvgIcon
        v-if="groups.maxPage > 1 && groups.currentPage < groups.maxPage"
        icon-class="more"
        popper-class="more-group"
        @click="requestNextGroup(++groups.currentPage)"
    /></el-scrollbar>
  </div>
</template>

<script lang="ts" setup>
import { ref, nextTick } from "vue";
import { useFriendPinia } from "@/pinia/friend";
import { storeToRefs } from "pinia";
import { ElMessage } from "element-plus";
import type { ElScrollbar } from "element-plus";
import handleToTags from "@/plugins/handleToTags";

const props = withDefaults(
  defineProps<{
    disabled?: boolean;
  }>(),
  {
    disabled: false,
  }
);

const emits = defineEmits<{
  (e: "change", tag: string): void;
}>();

const friendStore = useFriendPinia();
const { groups } = storeToRefs(friendStore);

/**
 * 当前用户所选择的标签值
 */
const tag = ref<string>();

// 处理过后的标签数据
const tags = ref<Map<string, { type: "" | "success" | "info" | "warning" | "danger" }>>(
  handleToTags(groups.value.value)
);

// 是否正在请求下一页的分组情况
const isRequestNextPageGroup = ref<boolean>(false);
const elScrollRef = ref<typeof ElScrollbar>();
const tagRef = ref<HTMLDivElement>(document.createElement("div"));

// 选择分组标签
const selectTag = (name: string) => {
  if (!props.disabled && tag.value !== name) {
    tag.value = name;
    emits("change", name);
  }
};

// 请求下一页的分组情况
const requestNextGroup = (page: number) => {
  if (!isRequestNextPageGroup.value) {
    isRequestNextPageGroup.value = true;
    friendStore
      .getUserGroups({ page })
      .then((payload: { code: number; value: string[] }) => {
        isRequestNextPageGroup.value = false;
        if (payload.code === 1) {
          const newTagData = handleToTags(payload.value);
          for (const [key, { type }] of newTagData.entries())
            tags.value.set(key, { type });
          const ele = tagRef.value.getElementsByClassName(
            "el-scrollbar__wrap"
          )[0] as HTMLElement;
          nextTick(() => {
            const top: number = ele.scrollHeight - ele.offsetHeight;
            top > 0 && nextTick(() => elScrollRef.value!.setScrollTop(top));
          });
        } else
          ElMessage({
            type: "error",
            message: "加载失败",
            duration: 1500,
          });
      })
      .catch(() => {
        isRequestNextPageGroup.value = false;
        ElMessage({
          type: "error",
          message: "加载失败",
          duration: 1500,
        });
      });
  }
};
</script>

<style lang="scss" scoped>
.tag-item {
  cursor: pointer;
  margin: 0 8px 8px 0;
}

.more-group {
  font-size: 23px;
  cursor: pointer;
  margin-left: 6px;
  vertical-align: middle;
}
</style>
